<template>
  <div>
    <!--    内容区域-->
    <el-card class="hardwareCard">
      <!-- 硬件表单-->
      <el-form ref="hardwareDetailRef" :rules="hardwareDetailRules" :model="hardwareDetail" label-width="100px"
               class="hardware_form">
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="硬件名称" prop="name">
              <el-input v-model="hardwareDetail.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="mac" prop="mac">
              <el-input v-model="hardwareDetail.mac"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="序列号" prop="serialNumber">
              <el-input v-model="hardwareDetail.serialNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="ip" prop="ip">
              <el-input v-model="hardwareDetail.ip"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="官网" prop="website">
              <el-input v-model="hardwareDetail.website"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="生产日期" prop="dateProduction">
              <el-date-picker v-model="hardwareDetail.dateProduction"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="生产者" prop="producers">
              <el-input v-model="hardwareDetail.producers"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="类型" prop="type">
              <el-select v-model="hardwareDetail.type" filterable placeholder="请选择硬件类型">
                <el-option v-for="item in types" :key="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="文档地址" prop="document">
              <el-input v-model="hardwareDetail.document"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="位置" prop="position">
              <el-cascader v-model="hardwareDetail.position" :options="positions"
                           :props="{ expandTrigger: 'hover' }"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="2">
            <el-form-item label="描述" prop="description">
              <el-input v-model="hardwareDetail.description" type="textarea" maxlength="50" rows="2"
                        show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-divider>硬件图片，点击更改</el-divider>
          <el-row type="flex" style="display: flex;flex-wrap: wrap ">
            <el-upload
                ref="moreupload"
                action="#"
                multiple
                :show-file-list="true"
                list-type="picture-card"
                :limit="10"
                :auto-upload="false"
                :file-list="showlist"
                :http-request="Uploaddetailsrc"
                :on-change="handlesrcschange"
                :on-remove="handlesrcRemove"
                :before-upload="beforeUpload"
                :on-preview="handlePictureCardPreview"
            >
              <div slot="tip" class="el-upload__tip">请上传图片(jpeg)格式文件</div>
              <i class="el-icon-plus" style="width: 20%"></i>
            </el-upload>
          </el-row>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <!-- 按钮区域-->
        <el-form-item>
          <el-row type="flex" justify="space-around">
            <el-button type="primary" size="medium" @click="submitform" class="submitbutton">
              提交
            </el-button>
            <el-button type="primary" size="medium" @click="resetform" class="submitbutton">
              重置
            </el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>

export default {
  name: "editHardware",
  props: ['editForm'],
  watch: {
    editForm: {
      handler(val) {
        this.hardwareDetail = JSON.parse(JSON.stringify(val.hardware))
        this.originDetail = val.hardware
        this.showlist = JSON.parse(JSON.stringify(val.images))
        this.ids = JSON.parse(JSON.stringify(val.ids))
      }
    }
  },
  data() {
    return {

      hardwareDetail: JSON.parse(JSON.stringify(this.editForm.hardware)),
      originDetail: this.editForm.hardware,
      photos: [],
      originPhotos: [],
      hardwareDetailRules: {
        // title: [
        //   {required: true, message: "please input the hardware name", trigger: "blur"}
        // ],
        // connect: [
        //   {required: true, message: "please input the hardware connect", trigger: "blur"},
        //   {validator: validateConnect, trigger: "blur"}
        // ]
      },
      ids: JSON.parse(JSON.stringify(this.editForm.ids)),
      DIds: [],
      showlist: JSON.parse(JSON.stringify(this.editForm.images)),
      uploadFiles: [],
      dialogImageUrl: '',
      dialogVisible: false,
      width: 200,
      height: 200,
      types: ["基础设备", "电脑外设", "配件及数据线", "物联网设备"],
      positions: [{
        value: '研究院四楼',
        label: "研究院四楼",
        children: [
          {
            value: '四楼实验室',
            label: "四楼实验室",
          },
          {
            value: '北423',
            label: "北423",
          },
        ]
      },
        {
          value: '研究院五楼',
          label: "研究院五楼",
          children: [
            {
              value: '中厅510',
              label: "中厅510",
            },
            {
              value: '北517',
              label: "北517",
            }
          ]
        }
      ]
    }
  }
  ,
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
    ,
    beforeUpload(file) {
      const imageType = (file.type === "image/jpeg");
      const imageSize = file.size / 1024 / 1024 < 16;
      if (!imageType) {
        this.$message.error("上传照片只能是JPG！");
      }
      if (!imageSize) {
        this.$message.error("上传照片大小不能超过 16MB！");
      }
      return imageSize && imageType;
    },
    handlesrcRemove(file, fileList) {
      this.showlist = fileList
      Array.prototype.remove = function (val) {
        for (let i = 0; i < this.length; i++) {
          if (this[i].src === val) {
            this.splice(i, 1);
            break;
          }
        }
      };
      let index = this.uploadFiles.indexOf(file)
      if (index !== -1) {
        this.uploadFiles.splice(index, 1)
      }
      if (file.hasOwnProperty('id')) {
        this.DIds.push(file.id);
      }
    },
    handlesrcschange(file, filelist) {
      this.showlist = filelist
      this.uploadFiles.push(file)
    },
    async Uploaddetailsrc() {
      let filelist = this.uploadFiles
      let i = 0;
      while (i < filelist.length) {
        let formData = new FormData()
        formData.append("file", filelist[i].raw)
        formData.append("hardwareId", this.hardwareDetail.id)
        let {data: res} = await this.$http.post('uploadHardwareImg', formData);
        i++;
      }
    },
    submitform() {//点击提交绑定事件
      //判断是否有更改操作
      if (JSON.stringify(this.originDetail) !== JSON.stringify(this.hardwareDetail)) {
        // 如果有更改操作，先检验表单
        this.$refs.hardwareDetailRef.validate(async valid => {
              if (!valid) return;
              // 发起请求
              this.hardwareDetail.position = this.hardwareDetail.position.toString();
              const {data: res} = await this.$http.put("editHardware", this.hardwareDetail);
              if (res.msg != "success") return this.$message.error("操作失败！！！");
              this.$message.success("操作成功！！！");
            }
        )
        ;
      }
      if (this.uploadFiles.length !== 0) {
        this.$refs.moreupload.submit()
      }
      if (this.DIds.length !== 0) {
        let param = new FormData()
        param.append("DIds", this.DIds)
        const {data: res} = this.$http.delete("delImageByIds?DIds=", param);
        if (res.msg != "success") {
          return this.$message.error("操作失败！！！");
        }
        return this.$message.success("操作成功！！！");
      }
      this.$emit("closeEditDialog")
    }
    ,
    resetform() {
      this.showlist = this.editForm.images
      this.uploadFiles = [];
      this.DIds = [];
      this.$refs.hardwareDetailRef.resetFields()
    }
    ,
  }
}
</script>

<style scoped>

.hardwareCard {
  margin: 20px auto;
  height: 100%;
  width: 100%;
}
</style>